package com.jacobson.huobi.mvp

import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.animation.LinearInterpolator
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.core.widget.adapter.ListRecyclerAdapter
import com.jacobson.huobi.R
import com.jacobson.huobi.components.SpaceItemDecoration
import com.jacobson.huobi.di.components.DaggerSymbolSearchActivityComponent
import com.jacobson.huobi.di.modules.SymbolSearchActivityModule
import com.jacobson.huobi.entities.SymbolInfo
import com.jacobson.huobi.entities.events.UpdateEvent
import com.jacobson.huobi.entities.websocket.RefreshSymbolResp
import com.jacobson.huobi.mvp.adapters.SymbolAdapter
import com.jacobson.huobi.mvp.contract.SymbolContract
import com.jacobson.huobi.utils.ComparableHelper
import com.jacobson.huobi.utils.ResourcesUtil
import kotlinx.android.synthetic.main.activity_search_symbol.*
import org.simple.eventbus.Subscriber
import javax.inject.Inject

@Immersive(fitSystemWindows = false)
class SymbolSearchActivity: BaseMvpActivity<SymbolContract.Presenter>(),
    SymbolContract.View {
    @field:Inject
    lateinit var symbolAdapter: SymbolAdapter
    @field:Inject
    lateinit var symbolList: MutableList<SymbolInfo>
    private var animator: ValueAnimator? = null
    private var isSelected = false
    private var type = 0
    private var filterFavorite = false
    private var filterAnalysis = false
    private val handler = Handler(Looper.getMainLooper())
    private var hadInjected = false

    private var keyword: String? = null
    private val finishSmartRefreshRunnable = Runnable {
        smartRefreshLayout.finishRefresh(false)
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerSymbolSearchActivityComponent.builder()
            .appComponent(appComponent)
            .symbolSearchActivityModule(SymbolSearchActivityModule(this))
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
        hadInjected = true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor =
                ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
        var m = windowManager
        var d = m.defaultDisplay
        var p = window.attributes
        p.height = (d.getHeight() * 0.6).toInt() // 高度设置为屏幕的1.0
        p.width =  (d.getWidth() * 1.0).toInt() // 宽度设置为屏幕的0.8
        p.alpha = 1.0f // 设置本身透明度
        p.dimAmount = 0.0f // 设置黑暗度
        window.attributes = p
        window.setGravity(Gravity.BOTTOM)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_search_symbol
    override fun initData(savedInstanceState: Bundle?) {
//        update2Position(DEFAULT_POSITION)
        smartRefreshLayout.setEnableLoadMore(false)
        smartRefreshLayout.setOnRefreshListener {
            presenter.updateSymbolList(getMarketName())
            handler.postDelayed(finishSmartRefreshRunnable, 5000)
        }
        smartRefreshLayout.setEnableLoadMore(false)
        smartRefreshLayout.setOnRefreshListener {
            presenter.updateSymbolList(getMarketName())
            handler.postDelayed(finishSmartRefreshRunnable, 5000)
        }
        symbolAdapter.setOnItemClickListener(object :
            ListRecyclerAdapter.OnItemClickListener<SymbolInfo> {
            override fun onItemClick(dataList: List<SymbolInfo>, data: SymbolInfo, position: Int) {
                symbolAdapter.setExpandPosition(position)
            }
        })
        with(recyclerView) {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(3f))
            adapter = symbolAdapter
        }
        updateShowDataList()

    }


    @Subscriber
    private fun onUpdate(updateEvent: UpdateEvent) {
//        topTabContainer?.notifyNumberAlarm(symbolList.filter { it.market == getMarketName()})
//        if (updateEvent.useKeyword) {
//            keyword = updateEvent.keyword
//        }
        updateShowDataList()
    }

    @Subscriber
    private fun onRefreshSymbolResp(refreshSymbolResp: RefreshSymbolResp) {
        this?.runOnUiThread {
            handler.removeCallbacks(finishSmartRefreshRunnable)
            smartRefreshLayout?.finishRefresh()
        }
    }


    private fun updateShowDataList() {
        val show = symbolList.filter { symbolInfo ->

            if (keyword != null && (!symbolInfo.currency.contains(keyword!!) && !symbolInfo.transCurrency.contains(
                    keyword!!
                ))
            ) {
                return@filter false
            }
            if (filterFavorite) {
                return@filter symbolInfo.isFavorite
            }
            if (filterAnalysis) {
                return@filter symbolInfo.isAnalysis
            }
//            symbolInfo.volumeLevel == topTabContainer.selectedPosition
            true
        }

        symbolAdapter.update(show.sortedWith(ComparableHelper()))
    }


    override fun onNetworkUnavailable() {

    }

    private fun getMarketName(): String {
        return when (type) {
            1 -> "okex"
            2 -> "bian"
            3 -> "58coin"
            else -> "huobi"
        }
    }

    override fun onResume() {
        super.onResume()
//        if (isSelected) {
//            startAnimator()
//        }
    }

    override fun onPause() {
        super.onPause()
//        stopAnimationIfNeed()
    }

    private fun startAnimator() {
        if (!hadInjected) {
            return
        }
        stopAnimationIfNeed()
        animator = ValueAnimator.ofInt(0, 1, 0)
        with(animator!!) {
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            interpolator = LinearInterpolator()
            duration = 500
            addUpdateListener { animation ->
                if (recyclerView?.scrollState == 0) {
                    symbolAdapter.setTwinkling(animation.animatedValue == 0)
                }
            }
            start()
        }
    }

    private fun stopAnimationIfNeed() {
        animator?.run {
            removeAllUpdateListeners()
            end()
            cancel()
        }
        animator = null
    }

    companion object {
        fun startActivity(context: Context) {
            Intent(context, SymbolSearchActivity::class.java).run {
                context.startActivity(this)
            }
        }

        const val HUOBI = 0
        const val OKEX = 1
        const val BIAN = 2
        const val COIN_58 = 3
        const val DEFAULT_POSITION = 1

    }
}